#include "Clipboard.h"


void Clipboard::handleSelectionRequestEvent(XSelectionRequestEvent *req) {
	XSelectionEvent respond;
	auto_ptr<std::string> requestorName(window_->getDisplay()->getWindowName(req->requestor));
	if (req->target != window_->getDisplay()->getTargetsAtom()) {
		//std::cout << "SelectionRequest from " << *requestorName << "wants" <<req->target << " to be copied to his " << req->property <<std::endl;
	}
	if (req->target == XA_STRING) {
		window_->getDisplay()->setWindowProperty(req->requestor, req->property, Storage::get());
		respond.property=req->property;
		//log()<<"giving them '" << *Storage::getInstance()->get() <<"'"<<endl;
	} else if (req->target == window_->getDisplay()->getTargetsAtom()) {
		window_->getDisplay()->setWindowProperty(req->requestor, req->property);
		respond.property=req->property;
		//respond.target = XA_ATOM;
		//log()<<"giving them targets'"<<endl;
	} else {
		respond.property = None;
		//log()<<"They dont want our string :/, they ("<< *requestorName <<")want" <<req->target <<" "<< *window_->getDisplay()->getAtomName(req->target) << "to " << *window_->getDisplay()->getAtomName( req->property) <<endl;
		// we know bether ;)
	}
	respond.type= SelectionNotify;
	copyEventFields(respond, *req);
	window_->getDisplay()->sendEvent(req->requestor,(XEvent*)&respond);
}

void Clipboard::handleSelectionNotifyEvent(XSelectionEvent *e) {
	//log() << "SelectionNotify(conversion finished) "<< endl;

	//std::cout<< "target = " <<e->target << " property " << e->property <<endl;
	if (e->target != XA_STRING) {
		//printf ("It is not 'String' so it is not Ok\n");
	} else if (e->property != XA_COPYRIGHT) {
		//printf ("It is not teh right property 0_o\n");
	} else {
		std::auto_ptr<string> data(window_->getProperty(XA_COPYRIGHT));
		//log()<<"remebering '"<< *data << "'" << std::endl ;
		Storage::update(clipboard_, getLastOwnerName(), data.get());
		//log()<<"Now in storage: '"<< *Storage::get() <<"'"<<std::endl;
	}
	//log() << "finished coping so ... Yarr! "<< endl;
	this->hijack();
}


void Clipboard::handleSelectionClearEvent(XSelectionClearEvent *e __attribute__((unused))) {
	auto_ptr<string> ownerName(getOwnerName());
	//log() << "SelectionClear caused by"<< *ownerName <<endl;
	if (window_->getDisplay()->getSelectionOwner(clipboard_) == None) {
		this->hijack();
		return;
	}
	//log() << "wants to take our clippboard :/" << endl;
	this->convert(window_->getRawHandler(), XA_COPYRIGHT);
}
	
